<template>
  <el-dialog :destroy-on-close="true" :lock-scroll="false" :title="form_title" :visible.sync="visible"
             width="750px">
    <!--    form start   -->
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" :validate-on-rule-change="false">
      <el-form-item label="项目名称" prop="name">
        <el-input v-model="form.name" placeholder="名称最多不超过50个字符"/>
      </el-form-item>
      <el-form-item label="订单编号">
        <el-input v-model="form.order_number" placeholder="请输入订单编号"/>
      </el-form-item>
      <el-form-item label="客户名称" prop="customer_name">
        <el-autocomplete v-model="form.customer_name" :fetch-suggestions="querySearchCustomer"
                         placeholder="请选择所属客户"
                         value-key="name" @select="handleSelectCustomer">
          <template v-slot="{ item }">
            <div style="color: #333;"><b>{{ item ? item.name : '' }}</b></div>
            <div class="name" style="margin-top: -4px; display: flex;">
              编号: <span style="margin-right: 14px;">{{ item.customer_number }}</span>
            </div>
          </template>
          <el-button slot="append" icon="el-icon-search"></el-button>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="项目负责人" prop="user_id">
        <el-select
          v-model="form.user_id"
          filterable
          remote
          @focus="remoteMethod('')"
          placeholder="请搜索项目负责人"
          :remote-method="remoteMethod"
          :loading="loading"
          style="width: 100%"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :value="item.id"
            :label="item.realname">
            <div><b>{{ item.realname }}</b> &nbsp; &nbsp;&nbsp;部门: <span>{{ item.dept_name }}</span> &nbsp;&nbsp;&nbsp;&nbsp;岗位:
              <span>{{ item.position_name }}</span></div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目协作人" prop="user_ids">
        <el-select
          v-model="form.user_ids"
          filterable
          multiple
          remote
          @change="$forceUpdate()"
          placeholder="请搜索项目协助人"
          :remote-method="remoteMethod"
          :loading="loading"
          style="width: 100%"
        >
          <el-option
            v-for="item in options1"
            :key="item.id"
            :value="item.id"
            :label="item.realname">
            <div><b>{{ item.realname }}</b> &nbsp; &nbsp;&nbsp;部门: <span>{{ item.dept_name }}</span> &nbsp;&nbsp;&nbsp;&nbsp;岗位:
              <span>{{ item.position_name }}</span></div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="施工地点:" prop="city">
        <div class="area">
          <City @areaChange="areaChange" :ids="cityName" ref="city"/>
        </div>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入详细地址"/>
      </el-form-item>

      <el-form-item label="所属区域" prop="zone_name">
        <el-select v-model="form.zone_name" class="ele-block" clearable placeholder="请选择所属区域">
          <el-option v-for="item in zones" :key="item" :label="item" :value="item"/>
        </el-select>
      </el-form-item>
      <el-form-item label="计划开始时间" prop="plan_start_at">
        <el-date-picker v-model="form.plan_start_at" class="c-picker" placeholder="选择计划开始时间" type="date"
                        :picker-options="pickerOptions0"
                        value-format="yyyy-MM-dd"/>
      </el-form-item>
      <el-form-item label="计划结束时间" prop="plan_complete_at">
        <el-date-picker v-model="form.plan_complete_at" class="c-picker" placeholder="选择计划结束时间" type="date"
                        :picker-options="pickerOptions1"
                        value-format="yyyy-MM-dd"/>
      </el-form-item>
      <el-form-item label="入场时间" prop="entry_at">
        <el-date-picker v-model="form.entry_at" class="c-picker" placeholder="选择计划结束时间" type="date"
                        value-format="yyyy-MM-dd"/>
      </el-form-item>
      <el-form-item label="计划工期">
        <el-input disabled :value="plan_duration">
          <span slot="suffix">天 </span>
        </el-input>
      </el-form-item>
      <el-form-item label="计划工时" v-if="type === 'add'" prop="plan_work_hour">
        <el-input-number v-model="form.plan_work_hour" :min="0">
        </el-input-number>
      </el-form-item>
      <el-form-item label="项目说明">
        <el-input v-model.trim="form.description" placeholder="请输入项目描述" :rows="4" type="textarea"/>
      </el-form-item>
      <el-form-item label="项目状态" v-if="type !== 'add'">
        <el-select v-model="form.status" class="ele-block" clearable placeholder="请选择项目状态">
          <el-option v-for="(item, index) in statusList" :key="index" :label="item.title" :value="item.code"/>
        </el-select>
      </el-form-item>
    </el-form>
    <!--    form end     -->
    <div slot="footer">
      <el-button @click="handleCancel()">取消</el-button>
      <el-button :loading="loading" type="primary" @click="handleSave('form')">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import City from '@/components/city'
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: "product-form",
  components: {City},
  props: ["statusList","zones"],
  watch: {
    'form.user_ids'(current) {
      console.log(current)
    }
  },
  data() {
    const validateAreas = (rule, value, callback) => {
      // 判断 country_id province_id city_id county_id 是否为空
      if (!this.city.length) {
        callback(new Error("请选择地区"));
      } else {
        callback();
      }
    };
    return {
      /*日期选择器限制*/
      pickerOptions0: {
        disabledDate: (time) => {
          if (this.form.plan_complete_at) {
            return time.getTime() >= new Date(this.form.plan_complete_at).getTime();
          } else {
            return false
          }
        }
      },
      pickerOptions1: {
        disabledDate: (time) => {
          return time.getTime() <= new Date(this.form.plan_start_at).getTime() - 24 * 60 * 60 * 1000;
        }
      },
      //省市区回显
      cityName: '',
      // 选择的省市区
      city: [],
      deptList: null,
      type: null,
      visible: false,
      rules: {
        city: [
          {required: true, trigger: "change", validator: validateAreas}
        ],
        name: [
          {required: true, message: "请输入项目名称", trigger: "blur"}
        ],
        customer_name: [{required: true, message: "请搜索客户名称", trigger: "change"}],
        user_id: [{required: true, message: "请搜索项目负责人", trigger: "blur"}],
        address: [
          {required: true, message: "请输入详细地址", trigger: "blur"}
        ],
        plan_start_at: [
          {required: true, message: "请选择计划开始日期", trigger: "blur"}
        ],
        plan_complete_at: [
          {required: true, message: "请选择计划结束日期", trigger: "blur"}
        ],
        plan_work_hour: [
          {required: true, message: "请输入计划工时", trigger: "blur"}
        ],
        entry_at:[
          {required: true, message: "请输入入场时间", trigger: "blur"}
        ],
        zone_name:[
          {required: true, message: "请输入所属区域", trigger: "blur"}
        ]
      },
      form: {
        plan_work_hour: 1,
        user_ids: [],
      },
      form_title: "",
      loading: false,
      deptLists: [],
      fileList: [],
      //选择文件保质期方式
      radio: "at",
      productType: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      options: [],
      options1: [],
    }
  },
  mounted() {
    this.remoteMethod('')
  },
  computed: {
    plan_duration() {
      let duration = 0
      if (this.form.plan_start_at && this.form.plan_complete_at) {
        const startDate = Date.parse(this.form.plan_start_at);
        const endDate = Date.parse(this.form.plan_complete_at);

        if (startDate == endDate) return duration = 1;
        if (startDate > endDate) return duration = 0;
        duration = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
      }
      return duration
    },
  },

  methods: {
    areaChange(val) {
      this.city = val
    },
    showDialog(type, form) {
      this.visible = true;
      this.type = type;
      type === "add" ? this.form = {plan_work_hour: 1} : this.form = {
        ...form,
      }
      if (type !== "add") {
        this.options = [{id: form.user_id, realname: form.user_name}]
        this.options1 = form.users.map(item => ({id: item.user_id, realname: item.user_name}))
        this.form.user_ids = form.users.map(item => item.user_id)
        this.city = [form.province_id.toString(), form.city_id.toString(), form.county_id.toString()]
        this.$nextTick(() => {
          this.$refs.city.addressIds = form.province_name ? form.province_name + '/' + form.city_name + '/' + form.county_name : ''
        })
        this.$forceUpdate()
      }
      this.form_title = (type === "add" ? "添加项目" : "修改项目");
    },
    /** 保存事件 **/
    handleSave(val) {
      this.$refs[val].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.form = Object.assign({}, this.form, {
          province_id: this.city[0],
          city_id: this.city[1],
          county_id: this.city[2]
        });
        this.type === "add" ? this.addProject(this.form) : this.editProject(this.form)
      });
    },
    // 新增项目
    addProject(params) {
      this.$http.post('/projects', params).then(res => {
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.handleCancel();
          this.$emit("reload")
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    // 编辑项目
    editProject() {
      this.loading = true;
      this.$http.put(`/projects/${this.form.id}`, this.form).then(res => {
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.handleCancel();
          this.$emit("reload")
        }
        this.loading = false;
      });
    },
    /** 取消事件 **/
    handleCancel() {

      this.visible = false;
      this.$refs['form'].resetFields();
    },
    /**--- 逻辑处理 start ---**/
    querySearchCustomer(query, cb) {
      this.$http.get("customers", {
        params: {
          keyword: query,
          page: 1,
          limit: 10
        }
      }).then((res) => {
        cb(res.data.data);
      });
    },
    handleSelectCustomer(item) {
      this.form.customer_id = item.id
    },
    querySearchType(query = '', cb) {
      // query = query ? query : ''
      this.$http.get(`/user/index?limit=20&realname=${query} `).then((res) => {
        cb(res.data.data.filter(item => {
          return item.position_id === 5
        }));
      });
    },
    arrayToTree(array, pid) {
      let result = []
      array.forEach(item => {
        if (item.pid === pid) {
          item.children = this.arrayToTree(array, item.id)
          result.push(item)
        }
      })
      return result
    },
    selectType(val) {
      this.form.warranty_type = val
      this.$forceUpdate()
    },
    remoteMethod(query = '') {
      this.loading = true
      this.$http.get(`/user/index?limit=10&realname=${query} `).then((res) => {
        if (res.data.code == 0) {
          this.options = res.data.data.filter(item => {
            return item.id !== 1
          })
          this.options1 = res.data.data.filter(item => {
            return item.id !== 1
          })
          this.loading = false
        }
      });
    },
    /**--- 逻辑处理 end ---**/
  }
}
</script>

<style scoped>
.area /deep/ .el-cascader {
  width: 100%;
}

/deep/ .el-input {
  width: 100%;
}

/deep/ .el-autocomplete {
  width: 100%;
}

</style>
